﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerArchitecture.Core;
using ComputerArchitecture.Core.Logging;
using ComputerArchitecture.Numbers;
using ComputerArchitecture.Units.Interfaces;

namespace ComputerArchitecture.Units.Shifted
{
    public class ShiftedCompareUnit : LoggingObject, IShiftedCompareUnit
    {
        #region Fields

        private readonly ISubstractUnit _substractUnit;

        #endregion

        #region Constructors

        public ShiftedCompareUnit(ILoggingService loggingService, ISubstractUnit substractUnit)
            : base(loggingService)
        {
            ArgumentValidator.NullValidate(substractUnit);
            _substractUnit = substractUnit;
        }

        #endregion

        int ICompareUnit.Compare(ISignedBitNumber first, ISignedBitNumber second)
        {
            return Compare(first, second, ShiftedBitNumber.GetOffset(first.Size));
        }

        public int Compare(ISignedBitNumber first, ISignedBitNumber second, ISignedBitNumber offset)
        {
            ArgumentValidator.NullValidate(first);
            ArgumentValidator.NullValidate(second);
            bool overflow;
            ISignedBitNumber firstComplement = _substractUnit.Substract(first, offset, out overflow);
            ISignedBitNumber secondComplement = _substractUnit.Substract(second, offset, out overflow);
            ISignedBitNumber result = _substractUnit.Substract(firstComplement, secondComplement, out overflow);
            return result.IsZero ? 0 : result.Sign;
        }
    }
}
